<template>
  <div style="display: inline-block" @click.stop>
    <el-popover
      ref="popover"
      placement="bottom"
      title="筛选依据"
      trigger="click"
    >

      <!--文本选择器-->
      <el-select
        style="width: 204px;"
        v-if="filterType == 'text'"
        v-model="conditionDomain.conditionType"
        placeholder="请选择条件"
        size="mini"
        clearable
        @clear="clearable"
      >
        <el-option
          style="font-weight: bolder"
          size="mini"
          v-for="(item, index) in textOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <!--数字选择器-->
      <el-select
        style="width: 204px;"
        v-if="filterType == 'number'"
        v-model="conditionDomain.conditionType"
        placeholder="请选择条件"
        size="mini"
        clearable
        @clear="clearable"
      >
        <el-option
          style="font-weight: bolder"
          size="mini"
          v-for="(item, index) in numberOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <!--时间选择器-->
      <el-select
        style="width: 204px;"
        v-if="filterType == 'date'"
        v-model="conditionDomain.conditionType"
        placeholder="请选择条件"
        size="mini"
        clearable
        @clear="clearable"
      >
        <el-option
          style="font-weight: bolder"
          size="mini"
          v-for="(item, index) in dateOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <!-- 单个文本框 -->
      <div v-if="filterType == 'text'" style="padding-top: 10px">
        <el-input
          style="width: 204px;"
          v-model.trim="conditionDomain.text"
          size="mini"
          clearable
          @clear="clearable()"
          placeholder="请输入查询内容"
          @keyup.native.enter="confirm()"
        />
      </div>
      <!-- 数值范围 -->
      <div v-else-if="filterType == 'number'" style="padding-top: 10px">
        <el-input
          style="width: 204px"
          v-model.trim="conditionDomain.startValue"
          size="mini"
          clearable
          type="number"
          step="1"
          :placeholder="numberPlaceholder"
        />
        <el-input
          v-if="conditionDomain.conditionType == 'bw'"
          v-model.trim="conditionDomain.endValue"
          size="mini"
          clearable
          step="0.01"
          style="margin-top: 10px"
          placeholder="请输入结束数值"
        />
      </div>
      <!-- 日期-->
      <div v-else-if="filterType == 'date'" style="padding-top: 10px">
        <el-date-picker
          v-if="conditionDomain.conditionType=='bw'"
          v-model="dateRange"
          style="width: 204px"
          size="mini"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </div>
      <!-- 复选框-->
      <div v-else-if="filterType == 'checkbox'">
        <el-checkbox-group v-model="conditionDomain.checkbox" style="width: 204px;">
          <el-checkbox
            v-for="(item, index) in customArrList"
            :key="index"
            :label="item.value"
          >{{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="text-right mgt10" style="padding-top: 10px;display: flex; justify-content: flex-end;">
        <el-select
          style="width: 70px; padding-right: 10px"
          v-model="conditionDomain.orderType"
          placeholder="正序"
          size="mini"
        >
          <el-option
            size="mini"
            v-for="(item, index) in orderOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          type="warning"
          size="mini"
          @click="reset"
        >重置
        </el-button>
        <el-button
          type="primary"
          size="mini"
          @click="confirm"
        >确定
        </el-button>
      </div>
      <!-- 标题-->
      <span
        slot="reference"
        :class="labelColor"
      >{{ column.label }} &nbsp;<i/>
      </span>
    </el-popover>
  </div>
</template>
<script>

export default {
  name: 'FilterHeader',
  props: {
    column: {
      type: Object,
      defalut: null
    },
    fieldName: {
      type: String,
      defalut: ''
    },
    tableName: {
      type: String,
      defalut: ''
    },
    filterType: {
      type: String,
      defalut: 'text'
    },
    customArrList: {
      type: Array,
      defalut: []
    },
    paramsPlusTemp: {
      type: Array,
      defalut: []
    }
  },
  data() {
    return {
      orderOptions: [{value: 'ASC', label: '升序'}, {value: 'DESC', label: '降序'}],
      textOptions: [{value: 'eq', label: '等于'}, {value: 'ne', label: '不等于'}, {
        value: 'contain',
        label: '包含'
      }, {value: 'excluding', label: '不包含'}, {value: 'startis', label: '开始是'}, {
        value: 'startisnot',
        label: '开始不是'
      }, {value: 'endis', label: '结束是'}, {value: 'endisnot', label: '结束不是'}],
      numberOptions: [{value: 'eq', label: '等于'}, {value: 'ne', label: '不等于'}, {
        value: 'lt',
        label: '小于'
      }, {value: 'gt', label: '大于'}, {value: 'le', label: '小于等于'}, {value: 'ge', label: '大于等于'}, {
        value: 'bw',
        label: '区间'
      }],
      dateOptions: [{value: 'bw', label: '区间'}, {value: 'after', label: '晚于今天（包含当天）'}, {
        value: 'before',
        label: '早于今天（包含当天）'
      }, {value: 'today', label: '今天'}, {value: 'yesterday', label: '昨天'}, {
        value: 'tomorrow',
        label: '明天'
      }, {value: 'thisweek', label: '本周'}, {value: 'thismonth', label: '本月'}],
      conditionDomain: {
        tableName: this.tableName,
        fieldName: this.column.property,
        conditionType: null,
        startValue: null,
        endValue: null,
        text: null,
        type: this.filterType,
        checkbox: [],
        orderType: 'ASC'
      },
      dateRange: [],
      tempData: [],
    }
  },
  computed: {
    numberPlaceholder() {
      if (this.conditionDomain.conditionType !== 'bw') {
        return '请输入数值'
      } else {
        return '请输入开始数值'
      }
    },
    // 有条件的话高亮显示标题
    labelColor() {
      switch (this.filterType) {
        case 'text':
          if (this.conditionDomain.text) {
            return 'heighLight'
          }
          return ''
        case 'number':
          if (this.conditionDomain.startValue || this.conditionDomain.endValue) {
            return 'heighLight'
          }
          return ''
        case 'date':
          if(this.conditionDomain.conditionType==='bw' && (this.conditionDomain.startValue && this.conditionDomain.endValue)){
            return 'heighLight'
          }else if(this.conditionDomain.conditionType && this.conditionDomain.conditionType!=='bw'){
            return 'heighLight'
          }
          return ''
        case 'checkbox':
          if (this.conditionDomain.checkbox.length > 0) {
            return 'heighLight'
          }
          return ''
      }
      return ''
    }
  },
  watch: {
    conditionDomain: {
      handler(newVal, oldVal) {
        let flag = false
        // console.log(this.paramsPlusTemp)
        if (this.paramsPlusTemp !== undefined) {
          this.tempData = JSON.parse(JSON.stringify(this.paramsPlusTemp))
          this.tempData.map(obj => {
            if (obj.fieldName === this.column.property) {
              flag = true
              obj.fieldName = this.conditionDomain.fieldName;
              obj.conditionType = this.conditionDomain.conditionType;
              obj.startValue = this.conditionDomain.startValue;
              obj.endValue = this.conditionDomain.endValue;
              obj.text = this.conditionDomain.text;
              obj.type = this.conditionDomain.type;
              obj.checkbox = this.conditionDomain.checkbox;
              obj.orderType = this.conditionDomain.orderType;
            }
            return obj // 不需要替换的对象返回原对象
          })
        } else {
          this.tempData = []
        }

        // 如果加入的新的筛选字段则更新父组件中的参数
        if (flag == false) {
          this.tempData.push(this.conditionDomain)
        }

        switch (this.filterType) {
          case 'text':
            if (!this.isEmptyStr(this.conditionDomain.conditionType) && this.isEmptyStr(this.conditionDomain.text)) {
              return
            }
            this.$emit('update:paramsPlusTemp', this.tempData)
            break
          case 'number':
            if (!this.isEmptyStr(this.conditionDomain.conditionType) && this.isEmptyStr(this.conditionDomain.startValue)) {
              return
            }
            break
          case 'date':
            console.log("watch",this.dateRange)
            if(this.conditionDomain.startValue && this.conditionDomain.endValue && this.dateRange.length === 0){
              this.dateRange.push(this.conditionDomain.startValue)
              this.dateRange.push(this.conditionDomain.endValue)
            }
            this.conditionDomain.startValue = this.dateRange[0] !== undefined ? this.dateRange[0] : this.conditionDomain.startValue
            this.conditionDomain.endValue = this.dateRange[1] !== undefined ? this.dateRange[1] : this.conditionDomain.endValue

            console.log("watchConditionDomain",this.conditionDomain)
            if (this.conditionDomain.conditionType === 'bw' && !this.isEmptyStr(this.conditionDomain.conditionType) && (this.isEmptyStr(this.conditionDomain.startValue) || this.isEmptyStr(this.conditionDomain.endValue))) {
              return
            }
            console.log("watchParamsPlusTemp",this.tempData)
            this.$emit('update:paramsPlusTemp', this.tempData)
            break
          case 'checkbox':
            if (this.conditionDomain.checkbox.length > 0) {
              this.$emit('update:paramsPlusTemp', this.tempData)
              this.conditionDomain.conditionType = 'in'
            }
            break
        }
      },
      deep: true
    }
  },
  mounted() {
    // 绑定事件
    this.$bus.$on('resetFilter', (data) => {
      this.clearCurrentField()
      this.$nextTick(() => {
        this.clearCurrentField()
      })
      // 条件设置为空
      this.reset()
    })
  },
  // 销毁对应自定义事件
  beforeDestroy() {
    this.$bus.$off('resetFilter')
  },
  created() {
    const headerFilters = localStorage.getItem("defaultHeader") === null ? null : JSON.parse(localStorage.getItem("defaultHeader"))
    if (headerFilters) {
      if (headerFilters[this.$route.name] !== undefined) {
        const arr = headerFilters[this.$route.name];
        const foundObject = arr.find(obj => obj.fieldName === this.column.property);
        if (foundObject) {
          this.conditionDomain = foundObject
        }
      }
    }
  },
  methods: {
    confirm() {
      let flag = false
      if (this.paramsPlusTemp !== undefined) {
        this.paramsPlusTemp.map(obj => {
          // console.log("obj.fieldName:",obj.fieldName)
          // console.log("this.column.property:",this.column.property)
          if (obj.fieldName === this.column.property) {
            flag = true
            obj.fieldName = this.conditionDomain.fieldName;
            obj.conditionType = this.conditionDomain.conditionType;
            obj.startValue = this.conditionDomain.startValue;
            obj.endValue = this.conditionDomain.endValue;
            obj.text = this.conditionDomain.text;
            obj.type = this.conditionDomain.type;
            obj.checkbox = this.conditionDomain.checkbox;
            obj.orderType = this.conditionDomain.orderType;
          }
          return obj;
        })
      } else {
        this.paramsPlusTemp = []
      }


      //  console.log("conditionDomain==>",this.conditionDomain)
      // 如果加入的新的筛选字段则更新父组件中的参数
      if (flag === false) {
        // console.log("组件的参数==》",this.paramsPlusTemp)
        this.paramsPlusTemp.push(this.conditionDomain)
      }

      switch (this.filterType) {
        case 'text':
          this.$emit('update:paramsPlusTemp', this.paramsPlusTemp)
          break
        case 'number':
          break
        case 'date':
          this.conditionDomain.startValue = this.dateRange[0]
          this.conditionDomain.endValue = this.dateRange[1]
          console.log("确定",this.conditionDomain.startValue)
          break
        case 'checkbox':
          this.conditionDomain.conditionType = 'in'
          break
      }
      setTimeout(()=>{
        this.$emit('update:paramsPlusTemp', this.paramsPlusTemp)
        this.$emit('handleQuery')
      })

      this.$refs.popover.doClose()
    },
    clearable() {
      this.clearCurrentField()
      this.$nextTick(() => {
        this.clearCurrentField()
      })
      this.$emit('update:paramsPlusTemp', this.paramsPlusTemp)
    },
    reset() {
      // 条件设置为空
      this.conditionDomain.conditionType = null
      this.conditionDomain.tableName = null
      switch (this.filterType) {
        case 'text':
          this.conditionDomain.text = '';
          break
        case 'number':
          this.conditionDomain.startValue = ''
          this.conditionDomain.endValue = ''
          break
        case 'date':
          this.dateRange = []
          this.conditionDomain.startValue = ''
          this.conditionDomain.endValue = ''
          break
        case 'checkbox':
          this.conditionDomain.checkbox = []
          break
      }
      this.conditionDomain.orderType = 'ASC';
    },
    clearCurrentField() {
      if(this.paramsPlusTemp === undefined || this.paramsPlusTemp.length === 0){
        return;
      }
      let index = this.paramsPlusTemp.findIndex((item) => {
        return item.fieldName === this.column.property
      })
      if (index < 0) {
        return
      }
      this.paramsPlusTemp.splice(index, 1)
    },
    isEmptyStr(s) {
      if (s == undefined || s == null || s === '') {
        return true
      }
      return false
    }
  }
}
</script>
<style scoped>
.label {
  user-select: none;
}

.heighLight {
  color: #409eff;
}

.filter-radio {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.el-radio {
  width: 45%;
  margin-right: 0
}

.el-select-dropdown__item {
  font-size: 10px;
}
</style>
